<template>
  <view class="h-screen flex flex-col items-center justify-center bg-gray-50 p-4">
    <view class="mx-4 rounded-xl bg-white p-4 shadow-md">
      <view class="mb-4 text-center text-lg font-bold">
        {{ $t('loginTitle') }}
      </view>

      <!-- 手机号 -->
      <uv-input v-model="phone" :placeholder="phonePlaceholder" clearable class="mb-4" />

      <!-- 验证码 + uv-code 倒计时按钮 -->
      <view class="mb-4 flex items-center">
        <uv-input v-model="code" :placeholder="codePlaceholder" clearable class="flex-1" />
        <uv-button type="primary" class="ml-3" :disabled="!canGetCode" @tap="sendPhoneCode">
          {{ btnText }}
        </uv-button>
        <uv-code ref="codeRef" :seconds="60" keep-running @change="onCodeChange" @end="onCodeEnd" />
      </view>

      <PrivacyAgree v-model="agreed" class="mb-4" />

      <!-- 登录按钮 -->
      <uv-button type="primary" :disabled="!isMobileValid || !isCodeValid || !agreed" @click="doLogin">
        {{ $t('loginBtn') }}
      </uv-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { toast } from '@climblee/uv-ui/libs/function/index.js'
import { mobile } from '@climblee/uv-ui/libs/function/test.js'
import { isH5 } from '@uni-helper/uni-env'
import { useRequest } from 'alova/client'
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { login, sendCode } from '@/api/authService'
import { t } from '@/locale'
import { useUserStore } from '@/store'
import { isPageTabbar } from '@/tabbar/store'
import { HOME_PAGE } from '@/utils'

// --- 表单状态 ---
const phone = ref('')
const code = ref('')
const agreed = ref(false)

const phonePlaceholder = ref(t('loginPhonePlaceholder'))
const codePlaceholder = ref(t('loginCodePlaceholder'))

const isMobileValid = computed(() => mobile(phone.value))
const isCodeValid = computed(() => code.value.length === 4)

// --- uv-code ref ---
const codeRef = ref<any>()

// --- 按钮状态和文案 ---
const canGetCode = computed(() => codeRef.value?.canGetCode !== false)
const btnText = ref(t('loginGetCode'))

// --- alova 请求 ---
const { send: requestSendCode, loading: sending } = useRequest(sendCode, { immediate: false })
const { send: requestLogin, loading: logining } = useRequest(login, { immediate: false })

// --- 获取验证码 ---
async function sendPhoneCode() {
  if (!isMobileValid.value) {
    toast(t('loginPhoneInvalid'))
    return
  }
  if (!canGetCode.value || sending.value)
    return

  try {
    await requestSendCode(phone.value)
    toast(t('loginCodeSent'))
    codeRef.value?.start() // 启动 uv-code 倒计时
  }
  catch (err: any) {
    console.error(err)
    toast(t('loginCodeSendFailed'))
  }
}

// --- uv-code 事件 ---
function onCodeChange(text: string) {
  // 倒计时文本变化，可用于额外 UI
  btnText.value = text
}
function onCodeEnd() {
  // 倒计时结束后的回调
}

// --- 登录 ---
const route = useRoute()
const userStore = useUserStore()
async function doLogin() {
  if (!agreed.value) {
    toast(t('loginAgreeTip'))
    return
  }
  if (logining.value)
    return

  try {
    const res = await requestLogin({ phone: phone.value, authCode: code.value, loginWay: 1 })
    userStore.setUserInfo(res)
    toast(t('loginSuccess'))

    const redirect = route.query.redirect
    const redirectStr = Array.isArray(redirect) ? redirect[0] : redirect || ''
    const decoded = decodeURIComponent(redirectStr)

    if (decoded) {
      if (isPageTabbar(decoded)) {
        uni.switchTab({ url: decoded }) // 小程序 Tabbar
      }
      else {
        // H5 使用 replaceState 替换历史，避免返回登录页
        // 其他端使用 redirectTo
        if (isH5) {
          window.history.replaceState({}, '', decoded)
          window.location.href = decoded
        }
        else {
          uni.redirectTo({ url: decoded })
        }
      }
    }
    else {
      if (isH5) {
        window.history.replaceState({}, '', HOME_PAGE)
        window.location.href = HOME_PAGE
      }
      else {
        uni.switchTab({ url: HOME_PAGE })
      }
    }
  }
  catch (err: any) {
    toast(t('loginFailed', { msg: err.message }))
  }
}
</script>

<style scoped></style>
